package com.mybatisflex.admin.controller;

import com.alibaba.fastjson.JSON;
import com.mybatisflex.admin.AppProperties;
import com.mybatisflex.admin.entity.AuditMessageMeta;
import com.mybatisflex.admin.service.AuditMessageMetaService;
import com.mybatisflex.admin.service.AuditMessageService;
import com.mybatisflex.admin.util.HashUtil;
import com.mybatisflex.admin.util.Result;
import com.mybatisflex.core.audit.AuditMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class MessageCollectController {

    private static final long TIMEOUT = 10 * 60 * 1000;

    @Resource
    private AuditMessageService auditMessageService;

    @Resource
    private AuditMessageMetaService auditMessageMetaService;


    @PostMapping("/message/collect")
    public Result index(@RequestParam("time") long time, @RequestParam("sign") String sign,
                        @RequestBody List<AuditMessage> messages) {

        if ((System.currentTimeMillis() - time) > TIMEOUT) {
            return Result.error(1, "请求超时，请重新发起请求");
        }

        String localSign = HashUtil.md5(AppProperties.messageSecretKey + time);
        if (!localSign.equals(sign)) {
            return Result.error(2, "数据签名错误");
        }

        for (AuditMessage collectMessage : messages) {

            com.mybatisflex.admin.entity.AuditMessage message = new com.mybatisflex.admin.entity.AuditMessage();
            message.setPlatform(collectMessage.getPlatform());
            message.setModule(collectMessage.getModule());
            message.setUrl(collectMessage.getUrl());
            message.setUser(collectMessage.getUser());
            message.setUserIp(collectMessage.getUserIp());
            message.setHostIp(collectMessage.getHostIp());
            message.setQuery(collectMessage.getQuery());
            message.setQueryParams(JSON.toJSONString(collectMessage.getQueryParams()));


            message.setQueryTime(new Date(collectMessage.getQueryTime()));
            message.setElapsedTime(collectMessage.getElapsedTime());

            message.setCreated(new Date());

            auditMessageService.save(message);

            Map<String, Object> metas = collectMessage.getMetas();
            if (metas != null && !metas.isEmpty()) {
                List<AuditMessageMeta> messageMetas = new ArrayList<>();
                metas.forEach((s, o) -> {
                    AuditMessageMeta meta = new AuditMessageMeta();
                    meta.setMessageId(message.getId());
                    meta.setMetaKey(s);
                    meta.setMetaValue(JSON.toJSONString(o));
                    messageMetas.add(meta);
                });
                auditMessageMetaService.saveBatch(messageMetas);
            }
        }

        return Result.success();
    }

}
